import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import cookieUtil from './cookie'
let jumpFlag = true
// 请求拦截
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, 
  timeout: 5000 // 请求超时
})
/**
 * 为了k8s发布问题改造的外链js方案,若实际开发中不需要云发布，
 * 则axios.defaults.baseURL需修改为process.env.VUE_APP_BASE_API
 */
service.defaults.baseURL =  window._global._BASEURL
axios.defaults.baseURL =  window._global._BASEURL
//处理get请求
function get(config = {}) {
	/**添加时间戳,防止ie有缓存*/
	const data =  Object.assign(config.params || {}, { time: new Date().getTime() });
	config.params = data
	return config
}

//处理post请求
function post(config = {}) {
	config.headers['Content-Type'] = 'application/json;charset=utf-8'
	return config
}

//处理put请求
function put(config = {}) {
	config.headers['Content-Type'] = 'application/json;charset=utf-8'
	return config
}

// 发送请求
service.interceptors.request.use(
  config => {
		switch(config.method.toUpperCase()){
			case 'GET':
					return get(config)
			case 'POST':
					return post(config)
			case 'PUT':
					return put(config)
			default:
					return config
		}
  },
  error => {
    // 请求失败
    return Promise.reject(error)
  }
)
// 响应拦截
service.interceptors.response.use(
  response => {
    let tmp = response.data
    if (typeof (tmp) === 'string') {
				try {
					tmp = JSON.parse(tmp)
				} catch (e) {
					console.log(e)
				}
		}
		if(tmp.succ == undefined){
			Promise.resolve({result:tmp})
		}else if(!tmp.succ){
			var result={
				succ:'fail',
				msg:tmp.errorMessage,
			}
			Promise.reject(result)
			return
		}else if (tmp.succ.toLowerCase() === "ok") {
			return tmp
		} else if (tmp.succ.toLowerCase() === "jump") {
			if (jumpFlag && tmp.result.redirect) {
				jumpFlag = false;
				window.location.href = tmp.result.redirect;
			}
		}else if (tmp.succ.toLowerCase() === "logout") {
			if (jumpFlag && tmp.result.logout && tmp.result.login) {
				jumpFlag = false;
				new Image().src = tmp.result.logout
				setTimeout(function(){
					store.dispatch('user/resetToken')
					cookieUtil.delAllCookie()
					window.location.href = tmp.result.login
				}, 100)
			}
		}else {
			Promise.reject(tmp)
		}
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
